package com.wt.springsamples.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.wt.springsamples.TestRestService;
import com.wt.springsamples.model.dto.UserLoginInfo;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.FileSystemResource;
import org.springframework.http.*;
import org.springframework.stereotype.Controller;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.util.StreamUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.client.ResponseExtractor;
import org.springframework.web.client.RestTemplate;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;

@Api("文件管理")
@Controller
@RequestMapping("/file")
public class FileController {

    @Autowired
    private RestTemplate restTemplate;

    @Autowired
    private TestRestService testRestService;

    @GetMapping("/submit0")
    @ResponseBody
    public String submit0(@RequestParam(value = "taskId") Integer taskId,HttpServletRequest request) throws Exception {
        return  String.valueOf(taskId);
    }

    @PostMapping("/submit")
    @ResponseBody
    public String upload(@RequestParam(value = "taskId") Integer taskId,HttpServletRequest request) throws Exception {
      return  String.valueOf(taskId);
    }

    @PostMapping("/submit1")
    @ResponseBody
    public String submit1(Integer taskId,HttpServletRequest request) throws Exception {
        return  String.valueOf(taskId);
    }

    @PostMapping("/submit2")
    @ResponseBody
    public String submit2(@RequestBody Integer taskId,HttpServletRequest request) throws Exception {
        return  String.valueOf(taskId);
    }


    @ApiOperation(value = "file:upload",nickname ="文件管理-上传")
    @PostMapping("/uploadFile")
    @ResponseBody
    public String upload(@RequestParam(value = "file") MultipartFile file,HttpServletRequest request) throws Exception {
        UserLoginInfo userLoginInfo  = JSON.parseObject(request.getParameter("info"), UserLoginInfo.class);
        String fileName = file.getOriginalFilename();
        file.transferTo(new File("D:\\FTP_DIR\\".concat(fileName)));
        return fileName+"|"+file.getName()+file.getResource().getDescription();
    }

    @PostMapping("/uploadFiles")
    @ResponseBody
    public String uploadFiles(@RequestParam(value = "files") MultipartFile[] files) throws Exception {
        for (MultipartFile multipartFile:files){
            String fileName = multipartFile.getOriginalFilename();
            multipartFile.transferTo(new File("D:\\FTP_DIR\\".concat(fileName)));
        }
        return "success";
    }

    @GetMapping("/sendFile")
    @ResponseBody
    public ResponseEntity sendFile(){
        String requestUrl = "http://localhost:8080/file/uploadFile";
        File file = new File("D:\\jasperreports-ultimate-guide-3v2_0.pdf");

        //设置请求头
        HttpHeaders headers = new HttpHeaders();
        //1.设置请求类型 上传文件必须用表单类型
        headers.setContentType(MediaType.MULTIPART_FORM_DATA);
        //2.设置内容长度，必须设置
        headers.setContentLength(file.length());
        //3.设置文件名称，处理文件名是中文的情况
        headers.setContentDispositionFormData("fileName", URLEncoder.encode(file.getName()));

        //4.设置请求体，注意是LinkedMultiValueMap
        MultiValueMap<String, Object> form = new LinkedMultiValueMap<>();
        //5.把文件填充到表单里，注意使用FileSystemResource
        form.add("file", new FileSystemResource(file));
        UserLoginInfo info  = new UserLoginInfo();
        info.setName("wangtao");
        info.setEmail("scwt@sina.cn");
        info.setUserId(2222L);
        form.add("info",info);
        HttpEntity requestEntity = new HttpEntity<>(form, headers);
        //6.发起请求
        ResponseEntity<String> responseEntity = restTemplate.postForEntity(requestUrl, requestEntity, String.class);

        return responseEntity;
    }

    @GetMapping("/sendFiles")
    @ResponseBody
    public ResponseEntity sendFiles(){
        String requestUrl = "http://localhost:8080/file/uploadFiles";
        File file = new File("D:\\jasperreports-ultimate-guide-3v2_0.pdf");

        //设置请求头
        HttpHeaders headers = new HttpHeaders();
        //1.设置请求类型 上传文件必须用表单类型
        headers.setContentType(MediaType.MULTIPART_FORM_DATA);
        //2.设置内容长度，必须设置
        headers.setContentLength(file.length());
        //3.设置文件名称，处理文件名是中文的情况
        headers.setContentDispositionFormData("fileName", URLEncoder.encode(file.getName()));

        //4.设置请求体，注意是LinkedMultiValueMap
        MultiValueMap<String, Object> form = new LinkedMultiValueMap<>();
        //5.把文件填充到表单里，注意使用FileSystemResource
        form.add("files", new FileSystemResource(new File("D:\\servlet-3_0-final-spec.pdf")));
        form.add("files", new FileSystemResource(file)); //相同的key会将文件添加到key代表的List中
        UserLoginInfo info  = new UserLoginInfo();
        info.setName("wangtao");
        info.setEmail("scwt@sina.cn");
        info.setUserId(2222L);
        form.add("info",info);
        HttpEntity requestEntity = new HttpEntity<>(form, headers);
        //6.发起请求
        ResponseEntity<String> responseEntity = restTemplate.postForEntity(requestUrl, requestEntity, String.class);

        return responseEntity;
    }

    @PostMapping("/receiveRequest")
    @ResponseBody
    public String  receiveRequest() throws InterruptedException {
        Thread.sleep(1000*10);
        return  "success";
    }

    @GetMapping("/sendRequestGet")
    @ResponseBody
    public String sendRequestGet(){
        String url = "https://render-test-zhuanqiao.migu.cn:8443/cloudrender/api/v1/edge/info";
        Map<String, String> uriVariables = new HashMap<>();
        uriVariables.put("fileId", "fileId");
        ResponseEntity<String> responseEntity = restTemplate.getForEntity(url,String.class,uriVariables);
        return responseEntity.getBody();
    }

    @GetMapping("/sendRequestJson")
    @ResponseBody
    public String sendRequestJson() throws ExecutionException, InterruptedException {
        UserLoginInfo info  = new UserLoginInfo();
        info.setUserId(-2L);
        Future<Integer> future = Executors.newSingleThreadExecutor().submit(() -> {
            testRestService.sendRequestJson();
            info.setUserId(0L);
            return info.getUserId().intValue();
        });
        if(future.get()==0L){
            return "success";
        }
        return "failed";
    }



    @GetMapping("/sendRequestDownload")
    @ResponseBody
    public String sendRequestDownload(HttpServletResponse response) throws ExecutionException, InterruptedException, IOException {
        // 请求地址
        String url = "http://localhost:8080/file/download";
        Map<String, String> uriVariables = new HashMap<>();
        uriVariables.put("fileId", "fileId");
        ResponseExtractor<Boolean> responseExtractor = clientHttpResponse -> {
            // 获取文件名称
            HttpHeaders headers = clientHttpResponse.getHeaders();
            ContentDisposition contentDisposition = headers.getContentDisposition();
            String filename = contentDisposition.getFilename();
            File savePath = new File("D:\\temp\\download\\"+ filename);
            try {
                // 1、先保存到临时文件
                boolean mkdirs = savePath.getParentFile().mkdirs();
                StreamUtils.copy(clientHttpResponse.getBody(), new FileOutputStream(savePath));
            } finally {
                // 3、清理临时文件和UUID目录
                if (savePath.exists()) {
                    boolean delete = savePath.delete();
                    boolean deleteDir = savePath.getParentFile().delete();
                }
            }
            return true;
        };
//        ResponseEntity<byte[]> responseEntity = restTemplate.exchange(url, HttpMethod.GET, null,
//                byte[].class, uriVariables);
//        // 设置请求头，直接用第三方文件服务的响应头
//        HttpHeaders headers = responseEntity.getHeaders();
//        headers.forEach((key, value) -> response.setHeader(key, value.get(0)));
//        // 获取整个文件内容的字节数组后拷贝写入到输出流: inputStream -> byte[] -> outputStream
//        String filename = "servlet-3_0-final-spec.pdf";
//        File savePath = new File("D:\\temp\\download\\"+ filename);
//        StreamUtils.copy(responseEntity.getBody(), new FileOutputStream(savePath));
        Boolean execute = restTemplate.execute(url, HttpMethod.GET, null, responseExtractor, uriVariables);
//        if(execute){
//            return "success";
//        }
        return  "success";
    }

    @ApiOperation(value = "file:download",nickname ="文件管理-下载")
    @GetMapping("/download")
    public ResponseEntity<byte[]> download(HttpServletRequest request, HttpServletResponse response) throws Exception {
        String fileId = request.getParameter("fileId");
        //获取ServletContext对象
        ServletContext servletContext = request.getServletContext();
        //获取服务器中文件的真实路径
        String realPath = servletContext.getRealPath("/static/img/yw.mp4");
        //创建输入流
        String fileName = "servlet-3_0-final-spec.pdf";
        InputStream is = new FileInputStream("D:\\FTP_DIR\\".concat(fileName));
        //创建字节数组
        //is.available() is字节流对应的所有字节数
        byte[] bytes = new byte[is.available()];
        //将流读到字节数组中
        is.read(bytes);
        //创建HttpHeaders对象设置响应头信息
        MultiValueMap<String, String> headers = new HttpHeaders();
        //设置要下载方式以及下载文件的名字
        headers.add("Content-Disposition", "attachment;filename=".concat(fileName));
        //设置响应状态码
        HttpStatus statusCode = HttpStatus.OK;
        //创建ResponseEntity对象
        ResponseEntity<byte[]> responseEntity = new ResponseEntity<byte[]>(bytes, headers, statusCode);
        //关闭输入流
        is.close();
        return responseEntity;
    }

    @GetMapping("/getAfJobOutput")
    public ResponseEntity<String>  getAfJobOutput(){
        String requestUrl = "http://localhost:51000/file/receiveRequest";
        //设置请求头
        String json = "{\n" +
                "    \"get\":\n" +
                "    {\n" +
                "        \"type\" : \"jobs\",\n" +
                "        \"ids\" : [1],\n" +
                "        \"mode\":\"output\"\n" +
                "    }\n" +
                "}";
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_JSON);
        headers.add("AFANASY",String.valueOf(json.length()));
        HttpEntity httpEntity = new HttpEntity<>(json, headers);
        //6.发起请求
        ResponseEntity<String> responseEntity = restTemplate.postForEntity(requestUrl, httpEntity, String.class);
        return responseEntity;
    }
}
